import type {
  IPostComment,
  IPostCommentChildReply,
  IPostCommentParentReply,
  IPostCommentReply,
} from '@/interfaces';
import { type ChangeEvent, useContext, useState } from 'react';
import {
  type UseInfiniteQueryResult,
  useMutation,
  useQueryClient,
} from '@tanstack/react-query';
import useToast, { LoginReminderContent } from '@/hooks/useToast';
import { createChildReply } from '@/services/api';
import sanitizeHtml from 'sanitize-html';
import Image from 'next/image';
import { getUserAvatar } from '@/lib/tool';
import Link from 'next/link';
import { PostIdPageContext } from '@/contexts/post-id';
import { AppContext } from '@/contexts/app';
import Spinner from '@/app/[locale]/component/spinner/spinner';

export default function ChildReply({
  query,
  childReplyItem,
  childReplyIndex,
  parentReplyItem,
  parentReplyIndex,
  replyItem,
  replyIndex,
  commentItem,
  commentIndex,
}: {
  query: UseInfiniteQueryResult<IPostCommentParentReply>;
  childReplyItem: IPostCommentChildReply;
  childReplyIndex: number;
  parentReplyItem: IPostCommentParentReply;
  parentReplyIndex: number;
  replyItem: IPostCommentReply;
  replyIndex: number;
  commentItem: IPostComment;
  commentIndex: number;
}) {
  const {
    source: { path },
    translatedFields,
    queryKey,
  } = useContext(PostIdPageContext)!;
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;
  const [replyContent, setReplyContent] = useState('');
  const { show } = useToast();
  const queryClient = useQueryClient();

  const createChildReplyMutation = useMutation(createChildReply);

  async function onClickPostReply() {
    try {
      if (!path.user) {
        show({
          title: translatedFields.notLoggedInPrompt,
          content: <LoginReminderContent />,
        });
        return;
      }

      const _replyContent = replyContent.trim();
      if (!_replyContent) {
        show({
          type: 'DANGER',
          message: translatedFields.replyContentEmptyError,
        });
        return;
      }

      const content = sanitizeHtml(_replyContent);
      if (!content) {
        show({
          type: 'DANGER',
          message: translatedFields.replyContentEmptyError,
        });
        return;
      }

      const parentReplyId = parentReplyItem.reply.id;
      await createChildReplyMutation.mutateAsync({
        data: {
          parentReplyId,
          content,
        },
      });

      if (queryKey.length > 0) {
        await queryClient.refetchQueries(queryKey, {}, { throwOnError: true });
      }

      setReplyContent('');
      show({
        type: 'SUCCESS',
        message: translatedFields.replyCompleted,
      });
    } catch (e) {
      createChildReplyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeReplyContent(e: ChangeEvent<HTMLTextAreaElement>) {
    setReplyContent(e.target.value);
  }

  return (
    <div className="hstack gap-4">
      <div style={{ width: 64, height: 64 }}>
        <Image
          className="rounded-circle object-fit-contain"
          src={getUserAvatar(childReplyItem.user, metadata).smallAvatarUrl}
          alt={childReplyItem.user.alias}
          width={64}
          height={64}
          placeholder="blur"
          blurDataURL={env.APP_BLUR_DATA_URL}
        />
      </div>

      <div className="vstack">
        <div className="mb-4">
          <div
            dangerouslySetInnerHTML={{
              __html: childReplyItem.reply.content ?? '',
            }}
          ></div>
        </div>

        <div>
          <Link
            href={`/users/${childReplyItem.user.id}`}
            className="text-secondary link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
          >
            {childReplyItem.user.alias}
          </Link>
          &nbsp;
          {path.user ? (
            <a
              className="user-select-none text-secondary link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
              data-bs-toggle="collapse"
              href={`#yw-r-c-${childReplyItem.reply.id}`}
              role="button"
              aria-expanded="false"
              aria-controls={`yw-r-c-${childReplyItem.reply.id}`}
            >
              {translatedFields.reply}
            </a>
          ) : (
            <span className="user-select-none text-secondary mx-2">
              {translatedFields.reply}
            </span>
          )}
          &nbsp;
          <Link
            href={`/users/${parentReplyItem.user.id}`}
            className="text-secondary link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
          >
            {parentReplyItem.user.alias}
          </Link>
          &nbsp;
          <span className="text-secondary">·</span>
          &nbsp;
          <span className="text-secondary">
            <time dateTime={childReplyItem.reply.createdOn}>
              {childReplyItem.reply._createdOnText}
            </time>
          </span>
        </div>

        {path.user && (
          <div className="collapse" id={`yw-r-c-${childReplyItem.reply.id}`}>
            <div>
              <textarea
                className="form-control my-3"
                rows={4}
                placeholder={translatedFields.enterReply}
                name="replyContent"
                value={replyContent}
                onChange={onChangeReplyContent}
              ></textarea>
              <button
                disabled={createChildReplyMutation.isLoading || !replyContent}
                onClick={onClickPostReply}
                type="button"
                className="btn btn-outline-primary my-3 w-100"
              >
                {createChildReplyMutation.isLoading ? (
                  <Spinner classs="me-2" />
                ) : (
                  <i className="bi bi-cursor me-2"></i>
                )}
                {translatedFields.postReply}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
